package org.ahuanlien.crm.service.impl;

import org.ahuanlien.crm.domain.Client;
import org.ahuanlien.crm.domain.Employee;
import org.ahuanlien.crm.domain.TransferRecord;
import org.ahuanlien.crm.mapper.ClientMapper;
import org.ahuanlien.crm.mapper.EmployeeMapper;
import org.ahuanlien.crm.mapper.TransferRecordMapper;
import org.ahuanlien.crm.query.transferRecordQueryObject;
import org.ahuanlien.crm.service.ITransferRecordService;
import org.ahuanlien.crm.util.PageResult;
import org.ahuanlien.crm.util.UserContext;
import org.ahuanlien.crm.vo.TransferRecordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class TransferRecordServiceImpl implements ITransferRecordService {

	@Autowired
	private TransferRecordMapper transferRecordMapper;

	@Autowired
	private ClientMapper clientMapper;

	@Autowired
    private EmployeeMapper employeeMapper;

	public PageResult query(transferRecordQueryObject qo) {
		int count = transferRecordMapper.queryForCount(qo);
		if (count == 0) {
			return new PageResult(count, Collections.EMPTY_LIST);
		}
		List<TransferRecord> result = transferRecordMapper.queryForList(qo);
		return new PageResult(count, result);
	}

	public void insert(TransferRecord record) {
		transferRecordMapper.insert(record);
	}

	public void insertTransferRecord(TransferRecordVO vo) {

        Employee currentUser = UserContext.getCurrentUser();
        Client client = clientMapper.selectByPrimaryKey(vo.getId());
        String newChargeEmp = employeeMapper.getEmpNameById(vo.getNewChargeEmp());
        TransferRecord transferRecord = new TransferRecord();
        transferRecord.setRemoveDate(new Date());
        transferRecord.setClientName(client.getClientName());
        transferRecord.setOldChargeEmp(client.getChargeEmp());
        transferRecord.setNewChargeEmp(newChargeEmp);
        transferRecord.setRemoveEmp(currentUser.getUsername());
        transferRecord.setRemark(vo.getRemark());
        transferRecordMapper.insert(transferRecord);
        clientMapper.updateChargeEmp(vo.getId(),newChargeEmp);
    }
}
